const FetchUtil = {

    /**
     * Fetches a URL and returns the response as a JSON object.
     * @param url
     * @param options
     * @param call
     * @returns {Promise<ReadableStreamReadValueResult<Uint8Array> | ReadableStreamReadDoneResult<Uint8Array>>}
     */
    jsonStream: async (url, options = {}, call) => {
        let token = localStorage.getItem('global_token');
        if (token){
            token = JSON.parse(token).token;
        }
        if(token){
            if (!options){
                options = {};
            }
            if (!options.headers){
                options.headers = {};
            }
            options.headers['Authorization'] = 'Bearer ' + token;
        }
        if (!call){
            call = (done, data) => {
                console.log(done, data);
            };
        }
        try {
            const response = await fetch(url, options);

            const reader = response.body.getReader();
            const decoder = new TextDecoder('utf-8');
            return reader.read().then(function processText({ done, value }) {
                if (done) {
                    call(true)
                    console.log('Stream finished');
                    return;
                }
                let allLine = decoder.decode(value);
                let lines = [allLine]
                if (allLine.concat('\n')){
                    lines = allLine.split('\n');
                }
                for(let i in lines){
                    let line = lines[i].trim();
                    if (line === ''){
                        continue;
                    }
                    if (line === '[DONE]'){
                        return reader.read().then(processText);
                    }
                    if (line.startsWith("data:")){
                        line = line.substring(5);
                    }
                    try {
                        const json = JSON.parse(line);
                        call(false, json);
                    }catch (e){
                        console.error('Error parsing JSON:', e, 'Line:', line);
                        throw e;
                    }
                }
                return reader.read().then(processText);
            });
        }catch (e){
            console.error("Error in jsonStream:", e);
            throw e;
        }
    },
}

export default FetchUtil;
